package com.itajk.calculationtest;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;

import android.content.DialogInterface;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    NavController controller;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //fragment就是MainActivity里面的容器
        controller = Navigation.findNavController(this,R.id.fragment);
        //页面左上角就会出现左上角返回导航
        NavigationUI.setupActionBarWithNavController(this,controller);
    }

    //返回的响应
    @Override
    public boolean onSupportNavigateUp() {
        //如果是在答题页面返回
        if (controller.getCurrentDestination().getId() == R.id.questionFragment){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.quit_dialog_title));
            //第二个参数为消息处理器
            builder.setPositiveButton(R.string.dialog_positive_message, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    controller.navigateUp();
                }
            });

            builder.setNegativeButton(R.string.dialog_negative_message, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            //创建对话框
            AlertDialog dialog = builder.create();
            dialog.show();

        }else if (controller.getCurrentDestination().getId() == R.id.titleFragment){
            //在主界面可以直接返回，退出应用
            finish();
        } else {
            controller.navigate(R.id.titleFragment);
        }
        return super.onSupportNavigateUp();
    }

    //手机返回键被按下的时候做的事情
    @Override
    public void onBackPressed() {
        //调用上面就行
        onSupportNavigateUp();
    }
}
